# 无参数方法
def greet
  puts "Hello, Ruby!"
end

greet  # 输出: Hello, Ruby!
# 输出: "Hello, Ruby!"

# 带参数方法
def add(a, b)
  a + b  # 隐式返回
end

puts add(3, 5)  # 输出: 8

# 默认参数
def say_hello(name="Ruby")
  puts "Hello, #{name}!"
end

say_hello        # 输出: Hello, Ruby!
say_hello("Tom") # 输出: Hello, Tom!

# 可变参数
def sum(*numbers)
  numbers.sum
end

puts sum(1, 2, 3)    # 输出: 6
puts sum(4, 5, 6, 7) # 输出: 22

# 关键字参数
def create_person(name:, age:, gender: "unknown")
  { name: name, age: age, gender: gender }
end

p create_person(name: "Alice", age: 25)
# 输出: {:name=>"Alice", :age=>25, :gender=>"unknown"}

# 显式返回
def max(a, b)
  return a if a > b
  b
end

puts max(10, 20)  # 输出: 20

# 多返回值（返回数组）
def min_max(array)
  [array.min, array.max]
end

min, max = min_max([3, 1, 4, 1, 5, 9])
puts "Min: #{min}, Max: #{max}"  # 输出: Min: 1, Max: 9

# 代码块参数
def repeat(n)
  n.times { yield if block_given? }
end

repeat(3) { puts "Hi hello!" }

# 输出:
# Hi hello!
# Hi hello!
# Hi hello!

# 方法别名
def old_method
  puts "This is old method"
end

alias new_method old_method

new_method  # 输出: This is old method

# 类方法
class Calculator
  def self.add(a, b)  # 类方法定义方式1
    a + b
  end

  class << self       # 类方法定义方式2
    def subtract(a, b)
      a - b
    end
  end
end

puts Calculator.add(5, 3)       # 输出: 8
puts Calculator.subtract(5, 3)   # 输出: 2

# 私有方法
class BankAccount
  def initialize(balance)
    @balance = balance
  end

  def deposit(amount)
    @balance += amount
    log_transaction("Deposit", amount)
  end

  # 定义私有方法，在 private 下的都是私有方法
  private
  def log_transaction(type, amount)
    puts "#{type}: #{amount}"
  end

  def log_transaction2(type, amount)
    puts "#{type}: #{amount}"
  end

  # 定义公共方法，在 public 下的都是公共方法
  public
  def get_balance
    p @balance
  end
end

account = BankAccount.new(100)
account.deposit(50)  # 输出: Deposit: 50
account.get_balance  # 输出: 150
# account.log_transaction("Test", 10)  # 会报错，私有方法不能直接调用
# account.log_transaction2("Test", 10)  # 会报错，私有方法不能直接调用

# 方法查询
puts "方法列表: #{BankAccount.instance_methods(false)}"
puts "类方法列表: #{BankAccount.methods(false)}"
# 输出:
# 方法列表: [:deposit, :get_balance]
# 类方法列表: []

# 方法重定义
def say_hi
  puts "Hi!"
end

say_hi  # 输出: Hi!

def say_hi
  puts "Hello!"
end

say_hi  # 输出: Hello!

# 方法缺失处理
class DynamicMethods
  def method_missing(name, *args)
    if name.to_s.start_with?('find_by_')
      puts "动态查找: #{name} 参数: #{args}"
    else
      super
    end
  end
end

dm = DynamicMethods.new
dm.find_by_name("Alice")  # 输出: 动态查找: find_by_name 参数: ["Alice"]